import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_regression
from sklearn.linear_model import Lasso
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

X, y = make_regression(n_samples=100, n_features=2, noise=0.5, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

alpha = 1.0
lasso = Lasso(alpha=alpha)

lasso.fit(X_train, y_train)

y_pred = lasso.predict(X_test)

mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error:{mse:.2f}")

# 绘制特征系数
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.scatter(X[:, 0], y, label="Feature 1")
plt.scatter(X[:, 1], y, label="Feature 2")
plt.xlabel("Features")
plt.ylabel("Target")
plt.title('Original Data')
plt.legend()

plt.subplot(1, 2, 2)
plt.bar(['Feature 1', 'Feature 2'], lasso.coef_)
plt.xlabel('Features')
plt.ylabel('Coefficient Value')
plt.title('Lasso Coefficients')
plt.show()
